package com.five.filter;

import com.five.jwt.JwtUtils;
import com.five.jwt.Payload;
import com.five.jwt.RsaUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.PublicKey;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


@Component
@Order(-1)
public class LoginFilter implements GlobalFilter {
    // 定义排除的路径列表
    private static final List<String> EXCLUDE_PATHS = Arrays.asList(
            "/register/**",
            "/login/**"
    );
    private final PathMatcher pathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();

        // 检查当前路径是否在排除列表中
        for (String excludePath : EXCLUDE_PATHS) {
            if (pathMatcher.match(excludePath, path)) {
                return chain.filter(exchange); // 直接放行
            }
        }
        //1 请求拦截
        String token = request.getHeaders().getFirst("token");
        if (!StringUtils.isEmpty(token)){
            try {
                PublicKey publicKey = RsaUtils.getPublicKey(URLDecoder.decode(
                        JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile(), "UTF-8"));
                Payload<Map> payload = JwtUtils.getInfoFromToken(token, publicKey, Map.class);
                Map userInfo = payload.getUserInfo();
                Object loginInfo = userInfo.get("loginInfo");
                if (loginInfo!= null){
                    return chain.filter(exchange);
                }
            } catch (Exception e) {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
        }
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

}